<?php

namespace App\Http\Controllers;

use App\Common\Sql;
use App\Exceptions\ApiException;
use App\Logic\MiGuLogic;
use Illuminate\Support\Facades\DB;

class BuyGold extends Base
{
    public function logic()
    {
        $uid    = $this->uid;
        $buy_id = (int)$this->param['buy_id'];
        $row    = Sql::select('t_gold_mall_conf', [['id', $buy_id]]);
        if (count($row) != 1) {
            return $this->returnError(1, "商品ID不存在");
        }
        $gold  = (int)$row[0]['gold'];
        $price = (int)$row[0]['price'];
        //检查钻石是否充
        $object = DB::table('t_player_info')->find($uid, ['gold', 'migu_id']);
        if (empty($object)) {
            throw new ApiException('查找玩家ID失败', 2);
        }
        $migu_info  = MiGuLogic::instance()->get_migu_user_info($object->migu_id);
        $MyDiamonds = $migu_info['diamond'];
        $MyGold     = $object->gold;
        if ($MyDiamonds < $price) {
            throw new ApiException('您的钻石不足请及时充值', 3);
        }
        //购买
        $ret = $this->sub_diamonds($object->migu_id, $uid,$price, "钻石兑换金币",'diamonds:'.$price.'-'.'gold:'.$gold,(string)$buy_id);
        if (!$ret) {
            return $this->returnError(3, "购买失败数据库错误");
        }
        $ret = $this->grant_golds($uid, $gold, "兑换金币", (string)$buy_id);
        if (!$ret) {
            return $this->returnError(3, "购买失败数据库错误");
        }
        $ret_data                 = array();
        $ret_data["cur_gold"]     = $MyGold + $gold;
        $ret_data["cur_diamonds"] = $MyDiamonds - $price;
        return $this->returnData($ret_data, 0, "购买成功");
    }

}
